<template>
  <div class="app-container">
    <el-card>
      <!-- 表格标题及搜索功能 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="课程">
          <el-select
            v-model="queryParams.cId"
            filterable
            placeholder="请选择课程"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in CourseData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试卷">
          <el-select
            v-model="queryParams.pId"
            filterable
            placeholder="请选择试卷"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in PaperData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-button type="primary" @click="getList">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <div>
          <el-button type="primary" @click="handleAdd">新增考试</el-button>
          <el-button
            type="danger"
            :disabled="multiple"
            @click="handleDelete"
          >批量删除</el-button>
        </div>
      </el-form>
      <el-table v-loading="loading" :data="examList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" />
        <el-table-column label="所属课程" align="center" prop="courseName" width="150"/>
        <el-table-column label="所属试卷" align="center" prop="paperName" width="150"/>
        <el-table-column label="考试名称" align="center" prop="name" />
        <el-table-column label="是否限制时间" align="center" prop="timeLimit" width="150">
          <template #default="{ row }">
            {{ row.timeLimit === 1 ? '限制时间' : '不限制时间' }}
          </template>
        </el-table-column>
        <el-table-column label="考试时长" align="center" prop="duration" />
        <el-table-column label="考试开始时间" align="center" prop="startTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考试结束时间" align="center" prop="endTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考前注意事项" align="center" prop="precaution" />
        <el-table-column label="是否需要密码" align="center" prop="permission" width="150">
          <template #default="{ row }">
            {{ row.permission === 1 ? '需要密码' : '不需要密码' }}
          </template>
        </el-table-column>
        <el-table-column label="考试密码" align="center" prop="password" />
        <el-table-column label="是否批改" align="center" prop="isMark" width="150">
          <template #default="{ row }">
            {{ row.isMark === 1 ? '已批改' : '未批改' }}
          </template>
        </el-table-column>
        <el-table-column label="未批改数" align="center" prop="ungradedNum" />
        <el-table-column label="未上交数" align="center" prop="unturnedNum" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['teacher:exam:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['teacher:exam:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

    </el-card>

    <!-- 抽屉框 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      size="40%"
      :with-header="true"
      append-to-body
    >
      <div class="drawer-container">
        <el-form ref="form" :model="form"  label-width="100px">
          <el-form-item label="选择课程" prop="cId">
            <el-select
              v-model="form.cId"
              :disabled="isUpdate"
              filterable
              placeholder="请选择课程"
              clearable
            >
              <el-option
                v-for="item in CourseData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择试卷" prop="pId">
            <el-select
              v-model="form.pId"
              :disabled="isUpdate"
              filterable
              placeholder="请选择试卷"
              clearable
            >
              <el-option
                v-for="item in PaperData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="考试名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入考试名称" />
          </el-form-item>

          <el-form-item label="限制时间" prop="timeLimit">
            <el-radio-group v-model="form.timeLimit">
              <el-radio :label=1>限制时间</el-radio>
              <el-radio :label=0>不限制时间</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="考试时长" v-if="form.timeLimit === 1" prop="duration">
            <el-input v-model="form.duration" placeholder="请输入考试时长" />
          </el-form-item>

          <el-form-item label="需要密码" prop="permission">
            <el-radio-group v-model="form.permission">
              <el-radio :label=1>需要密码</el-radio>
              <el-radio :label=0>不需要密码</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="设置密码" v-if="form.permission === 1" prop="password">
            <el-input
              type="password"
              v-model="form.password"
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="考试开始时间" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择考试开始时间"
            />
          </el-form-item>
          <el-form-item label="考试结束时间" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择考试结束时间"
            />
          </el-form-item>
          <el-form-item label="考前注意事项" prop="precaution">
            <el-input v-model="form.precaution" placeholder="请输入考前注意事项" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="drawer-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>


<script>
import { listExam, getExam, delExam, addExam, updateExam } from "@/api/teacher/exam";
import { listCourse } from "@/api/course/course";
import { listPaper } from "@/api/teacher/paper";

export default {
  name: "Exam",
  data() {
    return {
      loading: true,
      ids: [], // 批量删除的 ID
      single: true, // 单选
      multiple: true, // 多选
      showSearch: true, // 是否展示搜索
      total: 0, // 总条数
      examList: [], // 考试列表
      CourseData: [], // 课程数据
      PaperData: [], // 试卷数据
      title: "",
      open: false, // 弹窗开关
      isUpdate: false, // 判断是新增还是修改
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cId: null,
        pId: null,
      },
      form: {
        cId: null, // 课程ID
        pId: null, // 试卷ID
        name: null, // 考试名称
        duration: null, // 考试时长
        startTime: null, // 开始时间
        endTime: null, // 结束时间
        remark: null, // 备注
        timeLimit: 0, // 是否限制时间
        permission: 0, // 是否需要密码（0为不需要，1为需要）
        password: '', // 密码
        precaution: null

      },
      // 用于选择是否限制时间和是否需要密码
      permissionOptions: [
        { label: '需要密码', value: 1},
        { label: '不需要密码', value: 0 }
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      // 获取考试列表
      listExam(this.queryParams).then(response => {
        this.examList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      // 获取课程数据
      listCourse().then(response => {
        this.CourseData = response.rows;
      });
      // 获取试卷数据
      listPaper().then(response => {
        this.PaperData = response.rows;
      });
    },

    // 新增考试
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考试";
      this.isUpdate = false;
    },

    // 修改考试
    handleUpdate(row) {
      this.reset();
      getExam(row.id).then(response => {
        this.form = { ...response.data }; // 复制数据到form
        this.open = true;
        this.title = "修改考试";
        this.isUpdate = true;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保在提交之前清空字段
          const submitData = { ...this.form }; // 深拷贝表单数据
          if (submitData.timeLimit === 0) {
            submitData.duration = null; // 清空考试时长
          }
          if (submitData.permission === 0) {
            submitData.password = null; // 清空密码
          }

          console.log('Data to submit:', submitData); // 调试日志

          if (submitData.id != null) {
            updateExam(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExam(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    // 重置表单
    reset() {
      this.form = {
        cId: null,
        pId: null,
        name: null,
        duration: null,
        startTime: null,
        endTime: null,
        remark: null,
        timeLimit: 0,
        permission: 0,
        password: null,
        precaution:null
      };
    },

    // 取消操作
    cancel() {
      this.open = false;
      this.reset();
    },

    // 是否展示考试时长输入框
    showDurationInput() {
      return this.form.limitTime;
    },

    // 是否展示密码输入框
    showPasswordInput() {
      return this.form.permission === 1;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除考试编号为"' + ids + '"的数据项？').then(function() {
        return delExam(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>

<style scoped>
/* 美化样式 */
.app-container {
  background-color: #f7faff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}
.search-bar {
  background-color: #fff;
  padding: 15px 20px;
  border: 1px solid #e3e7f3;
  border-radius: 8px;
  margin-bottom: 20px;
}
.el-table th {
  background-color: #e8f4ff;
  color: #333;
  font-weight: bold;
  text-align: center;
}
.el-table td {
  text-align: center;
}
.el-pagination {
  margin: 20px 0;
  display: flex;
  justify-content: flex-end;
}
.drawer-container{
  padding-left: 20px;
}
</style>
